<?php

require_once 'Zend/Filter/Interface.php';

class Zend_Filter_ConvertNewlines implements Zend_Filter_Interface
{
    /**
     * Predefined line termination styles.
     */
    const STYLE_WINDOWS = 'WINDOWS';
    const STYLE_UNIX = 'UNIX';
    const STYLE_MAC = 'MAC';
    const STYLE_NATIVE = 'NATIVE';
    
    /**
     * The delimiter string this filter uses for line termination.
     * 
     * @var string
     */
    private $_delimiter = null;
    
    /**
     * Initialize Zend_Filter_Newlines object.
     * 
     * @param string $style     Predefined line terminatiln styles. One of STYLE_* constants.
     * @param string $delimiter Custom string line delimiter.
     */
    public function __construct($style, $delimiter = null)
    {
        $this->setStyle($style, $delimiter);
    }

    /**
     * Sets line termination style.
     * 
     * @param string $style     Predefined line terminatiln styles. One of STYLE_* constants.
     * @param string $delimiter Custom string line delimiter.
     * 
     * @return Zend_Filter_ConvertNewlines Provides fluent interface
     */
    public function setStyle($style, $delimiter = null)
    {
        if(!is_null($style)) {
            $style = strtoupper($style);

            switch($style) {
                case Zend_Filter_ConvertNewlines::STYLE_WINDOWS:
                    $this->_delimiter = "\r\n";
                    break;
                case Zend_Filter_ConvertNewlines::STYLE_UNIX:
                    $this->_delimiter = "\n";
                    break;
                case Zend_Filter_ConvertNewlines::STYLE_MAC:
                    $this->_delimiter = "\r";
                    break;
                case Zend_Filter_ConvertNewlines::STYLE_NATIVE:
                    $this->_delimiter = PHP_EOL;
                    break;
            }
        } else {
            $this->_delimiter = $delimiter;
        }
        
        return $this;
    }

    /**
     * Returns line delimiter string used by this filter.
     * 
     * @return string Line delimiter string
     */
    public function getDelimiter()
    {
        return $this->_delimiter;
    }

    /**
     * Declared in Zend_Filter_Interface
     *
     * Returns the string $value with line delimiters converted into chosen style.
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        return preg_replace('/\r\n|\n|\r/', $this->_delimiter, $value);
    }
}